﻿using System;
using System.Collections.Generic;
using System.Text;

namespace PCR.Logic
{
    using PCR.Base;

    /// <summary>
    /// A simple privilege manager class,
    /// only support one user and don't support user role
    /// </summary>
    internal class PrivilegeManager : IPrivilegeManager
    {
        IDatabase _database = null;
        
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="database">Database interface<param>
        public PrivilegeManager(IDatabase database)
        {
            System.Diagnostics.Debug.Assert(database != null);
            this._database = database;
        }
        
        /// <summary>
        /// Get the current user
        /// </summary>
        /// <returns>Return the current user interface, 
        /// return null if no user existed</returns>
        public IUser GetUser()
        {
            return this._database.Privilege.GetUser();
        }

        /// <summary>
        /// Update the user information
        /// </summary>
        /// <param name="user">The user instance need to update</param>
        /// <returns>true if successfully, false if failed</returns>
        public bool UpdateUser(IUser user)
        {
            System.Diagnostics.Debug.Assert(user != null);
            return UpdateUser(user.UserName, user.Password);
        }

        /// <summary>
        /// Update the user by user name and password
        /// </summary>
        /// <param name="userName">The user name</param>
        /// <param name="password">The user password</param>
        /// <returns>true if successfully, false if failed</returns>
        public bool UpdateUser(string userName, string password)
        {
            return this._database.Privilege.UpdateUser(userName, password);
        }

        /// <summary>
        /// Validate the user
        /// </summary>
        /// <param name="userName">User name</param>
        /// <param name="password">User password</param>
        /// <returns>true if user and password are both right,
        /// otherwise return false</returns>
        public bool ValidateUser(string userName, string password)
        {
            IUser user = this._database.Privilege.GetUser();
            
            // Should not be null
            System.Diagnostics.Debug.Assert(user != null);

            // Username should not compare the case, but password 
            // Should compare the case
            if (string.Compare(userName, user.UserName, true) == 0
                && string.Compare(password, user.Password, false) == 0)
            {
                return true;
            }

            return false;
        }
    }
}
